package com.Final.hj;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class SocketIoFragment extends Fragment implements View.OnClickListener {
    private final int DELAY = 6000;
    private ImageView seach_friend;

    private List<SocketData> socketList = new ArrayList<>();
    private ArrayAdapter adapter;
    private ListView socket_l_v;

    private Context socketContent;

    private String myId;
    private SocketData socketItem;

    //定时器

    Timer timer;
    TimerTask task;

    private ApplicationGetSocket appGetSocket;

    @Override
    public void onAttach(final Context context){
        super.onAttach(context);
        socketContent = context;
        //获取myId
        myId = LoginSQLManger.getInstance(socketContent).queryAll().getMyId();
        //第一次直接获取内容
//        initData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.socket, container, false);

        initView(view);
        Toast.makeText(getContext(), "哈哈",Toast.LENGTH_SHORT).show();
        //这里启动定时器
        getTimer();
        socket_l_v.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                socketItem = socketList.get(position);
                handler.sendEmptyMessage(1);
                //不管点击哪一项都跳转到发送消息页面把对方的用户名传递过去
                Intent intent = new Intent(socketContent, Chatpage.class);

                intent.putExtra("titleUname", socketList.get(position).getUname());
                intent.putExtra("flagId", socketList.get(position).getFlagId());
                intent.putExtra("toId", socketList.get(position).getId());
                intent.putExtra("uname", socketList.get(position).getOtherName());
                startActivity(intent);
            }
        });
        return view;
    }


    @Override
    public void onStop(){
        super.onStop();

//        if (timer != null) {
//            timer.cancel();
//            timer = null;
//        }
//        if (task != null) {
//            task.cancel();
//            task = null;
//        }

        Toast.makeText(getContext(), "结束了",Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onHiddenChanged(boolean hidden){
        super.onHiddenChanged(hidden);
        if(hidden){//结束的时候使用
            //停止定时器
            timer.cancel();
            timer = null;
            task.cancel();
            task = null;
            return;
        }else{
            //这里启动定时器
            getTimer();
        }
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    adapter = new SocketAdapter(socketContent, R.layout.socket_adapter, socketList);
                    socket_l_v.setAdapter(adapter);
                    break;
                case 1:
                    socketItem.setNoReadNum("0");
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    };


    //定时器
    public void getTimer(){
        if(timer != null && task != null){
            return;
        }

        timer = new Timer();

        task = new TimerTask() {

            @Override
            public void run() {
                try {
                    //可以使用一个Handler对象，将定时消息传递到界面线程
                    initData();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        timer.schedule(task, 0, DELAY);
    }

    public void initData(){
        //这里发送请求拿取好友列表 并且status时2的数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{

                    OkHttpClient client = new OkHttpClient();

                    Request request = new Request.Builder()
                            .url("http://192.168.43.124:8080/gflist?myId="+ myId)
                            .build();
                    Call call = client.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.i("TAG", e.toString());
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String string = response.body().string();

                            System.out.println("已经得到数据");
                            //调用函数解析json
                            parseData(string);
                        }
                    });

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //解析数据
    public void parseData(String strJson){

        socketList.clear();
        JsonParser parser = new JsonParser();
        JsonArray jsonArray = parser.parse(strJson).getAsJsonArray();
        Gson gson = new Gson();

        for (JsonElement user : jsonArray) {
            //使用GSON，直接转成Bean对象
            SocketData userBean = gson.fromJson(user, SocketData.class);
            socketList.add(userBean);
        }

        handler.sendEmptyMessage(0);

    }


    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.seach_friend:
                //跳转到查找朋友页面
                Intent intent = new Intent(socketContent, Socket_Add.class);
                startActivity(intent);
                break;
        }

    }

    public void initView(View v){
        seach_friend = (ImageView) v.findViewById(R.id.seach_friend);
        socket_l_v = (ListView) v.findViewById(R.id.socket_list);
        timer = new Timer();
        seach_friend.setOnClickListener(this);
    }
}
